<?php

namespace common\web;

use Yii;

/**
 * ErrorAction displays application errors using a specified view.
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ErrorAction extends \yii\web\ErrorAction {

    /**
     * Runs the action.
     *
     * @return string result content
     */
    public function run() {
        if ($this->layout !== null) {
            $this->controller->layout = $this->layout;
        }
        Yii::$app->getResponse()->setStatusCodeByException($this->exception);
        if (Yii::$app->getRequest()->getIsAjax() && !Yii::$app->getRequest()->getIsPjax()) {
            if (Yii::$app->getRequest()->getIsModal()) {
                return $this->renderModalResponse();
            }
            return $this->renderAjaxResponse();
        }

        return $this->renderHtmlResponse();
    }

    /**
     * Builds array of parameters that will be passed to the view.
     * @return array
     * @since 2.0.11
     */
    protected function getViewRenderParams() {
        return [
            'code' => $this->getExceptionCode(),
            'name' => $this->getExceptionName(),
            'message' => $this->getExceptionMessage(),
            'exception' => $this->exception,
        ];
    }

    /**
     * Builds string that represents the exception.
     * Normally used to generate a response to AJAX request.
     * @return string
     * @since 2.0.11
     */
    protected function renderModalResponse() {
        return $this->controller->renderAjax($this->view ?: $this->id, $this->getViewRenderParams());
    }

}
